Print Hello world!

Source Code

# This program prints Hello, world!

print('Hello, world!')

Output

Hello, world!

In this program, we have used the built-in print() function to print the string Hello, world! on our screen.

String is a sequence of characters. In Python, strings are enclosed inside single quotes, double quotes or triple quotes (''', """).

Add Two Numbers

Source Code

# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers
sum = float(num1) + float(num2)

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output

The sum of 1.5 and 6.3 is 7.8

Changing this operator, we can subtract (-), multiply (*), divide (/), floor divide (//) or find the remainder (%) of two numbers.

Source Code: Add Two Numbers Provided by The User

# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers
sum = float(num1) + float(num2)

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output


Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8

In this program, we asked user to enter two numbers and this program displays the sum of two numbers entered by user.

We use the built-in function input() to take the input. input() returns a string, so we convert it into number using the float() function.

Alternative to this, we can perform this addition in a single statement without using any variables as follows.

print('The sum is %.1f' %(float(input('Enter first number: '))+float(input('Enter second number: '))))

Although this program uses no variable (memory efficient), it is not quite readable. Some people will have difficulty understanding it. It is better to write clear codes. So, there is always a compromise between clarity and efficiency. We need to strike a balance.

Find the Square Root

In this program, you'll learn to find the square root of a number using exponent operator and cmath module.
# Python Program to calculate the square root

# Note: change this value for a different result
num = 8 

# uncomment to take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Output

The square root of 8.000 is 2.828

In this program, we store the number in num and find the square root using the ** exponent operator. This program works for all positive real numbers. But for negative or complex numbers, it can be done as follows.

Source code: For real or complex numbers using cmath module

# Find square root of real or complex numbers
# Import the complex math module
import cmath

# change this value for a different result
num = 1+2j

# uncommment to take input from the user
#num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

Output

The square root of (1+2j) is 1.272+0.786j

In this program, we use the sqrt() function in the cmath (complex math) module.

Notice that we have used the eval() function instead of float() to convert complex number as well. Also notice the way in which the output is formatted.

Look here for more about string formatting in Python.

Calculate the Area of a Triangle

In this program, you'll learn to calculate the area of a triangle and display it.

To understand this example, you should have the knowledge of following Python programming topics:

s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))

Source Code

# Python Program to find the area of triangle

a = 5
b = 6
c = 7

# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter
s = (a + b + c) / 2

# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output

The area of the triangle is 14.70

In this program, area of the triangle is calculated when three sides are given using Heron's formula.

If you need to calculate area of a triangle depending upon the input from the user, input() function can be used.

Solve Quadratic Equation

This program computes roots of a quadratic equation when coefficients a, b and c are known.

To understand this example, you should have the knowledge of following Python programming topics:

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

Source Code

# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module
import cmath

a = 1
b = 5
c = 6

# To take coefficient input from the users
# a = float(input('Enter a: '))
# b = float(input('Enter b: '))
# c = float(input('Enter c: '))

# calculate the discriminant
d = (b**2) - (4*a*c)

# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

Output

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

We have imported the cmath module to perform complex square root. First we calculate the discriminant and then find the two solutions of the quadratic equation.

You can change the value of a, b and c in the above program and test this program.

Swap Two Variables

In this example, you will learn to swap two variables by using a temporary variable and, without using temporary variable.

To understand this example, you should have the knowledge of following Python programming topics:

# Python program to swap two variables

# To take input from the user
# x = input('Enter value of x: ')
# y = input('Enter value of y: ')

x = 5
y = 10

# create a temporary variable and swap the values
temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Output

The value of x after swapping: 10
The value of y after swapping: 5

In this program, we use the temp variable to temporarily hold the value of x. We then put the value of y in x and later temp in y. In this way, the values get exchanged.

Source Code: Without Using Temporary Variable

In python programming, there is a simple construct to swap variables. The following code does the same as above but without the use of any temporary variable.

x,y = y,x

If the variables are both numbers, we can use arithmetic operations to do the same. It might not look intuitive at the first sight. But if you think about it, its pretty easy to figure it out.Here are a few example

Addition and Subtraction

x = x + y
y = x - y
x = x - y

Multiplication and Division

x = x * y
y = x / y
x = x / y

XOR swap

This algorithm works for integers only

x = x ^ y
y = x ^ y
x = x ^ y

Generate a Random Number

Generate a Random Number

In this example, you will learn to generate a random number in Python.

Source Code

# Program to generate a random number between 0 and 9

# import the random module
import random

print(random.randint(0,9))

Output

5

Note that, we may get different output because this program generates random number in range 0 and 9. The syntax of this function is:

random.randint(a,b)

This returns a number N in the inclusive range [a,b], meaning a <= N <= b, where the endpoints are included in the range.

Convert Kilometers to Miles

In this program, you'll learn to convert kilometers to miles and display it.

To understand this example, you should have the knowledge of following Python programming topics:

kilometers = 5.5

# To take kilometers from the user, uncomment the code below
kilometers = float(input("Enter value in kilometers"))

# conversion factor
conv_fac = 0.621371

# calculate miles
miles = kilometers * conv_fac
print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))

Output

5.500 kilometers is equal to 3.418 miles

Note: To test the program, change the value of kilometers.

Your turn: Modify the above program to convert miles to kilometers using the following formula and run it.

kilometers = miles / conv_fac

Convert Celsius To Fahrenheit

In this program, you'll learn to convert Celsuis to Fahrenheit and display it.

To understand this example, you should have the knowledge of following Python programming topics:

celsius * 1.8 = fahrenheit - 32

Source Code

# Python Program to convert temperature in celsius to fahrenheit

# change this value for a different result
celsius = 37.5

# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

Output

37.5 degree Celsius is equal to 99.5 degree Fahrenheit

To test, modify the above program to convert to convert Fahrenheit to Celsuis using the following formula

celsius = (fahrenheit - 32) / 1.8

Check if a Number is Positive, Negative or 0

In this example, you will learn to check whether a number entered by the user is positive, negative or zero. This problem is solved using if...elif...else and nested if...else statement.

To understand this example, you should have the knowledge of following Python programming topics:

num = float(input("Enter a number: "))
if num > 0:
   print("Positive number")
elif num == 0:
   print("Zero")
else:
   print("Negative number")

Here, we have used the if...elif...else statement. We can do the same thing using nested if statements as follows.

Source Code: Using Nested if

num = float(input("Enter a number: "))
if num >= 0:
   if num == 0:
       print("Zero")
   else:
       print("Positive number")
else:
   print("Negative number")

The output of both programs will be same.

Output 1

Enter a number: 2
Positive number

Output 2

Enter a number: 0
Zero

A number is positive if it is greater than zero. We check this in the expression of if. If it is False, the number will either be zero or negative. This is also tested in subsequent expression.

Check if a Number is Odd or Even

In this example, you will learn to check whether a number entered by the user is even or odd.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python program to check if the input number is odd or even.
# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.

num = int(input("Enter a number: "))
if (num % 2) == 0:
   print("{0} is Even".format(num))
else:
   print("{0} is Odd".format(num))

Output 1

Enter a number: 43
43 is Odd

Output 2

Enter a number: 18
18 is Even

In this program, we ask the user for the input and check if the number is odd or even.

Check Leap Year

In this program, you will learn to check whether a year is leap year or not. We will use nested if...else to solve this problem.

To understand this example, you should have the knowledge of following Python programming topics:

2017 is not a leap year
1900 is a not leap year
2012 is a leap year
2000 is a leap year

Source Code

# Python program to check if the input year is a leap year or not

year = 2000

# To get year (integer input) from the user
# year = int(input("Enter a year: "))

if (year % 4) == 0:
   if (year % 100) == 0:
       if (year % 400) == 0:
           print("{0} is a leap year".format(year))
       else:
           print("{0} is not a leap year".format(year))
   else:
       print("{0} is a leap year".format(year))
else:
   print("{0} is not a leap year".format(year))

Output

2000 is a leap year

You can change the value of year in the source code and run it again to test this program.

Find the Largest Among Three Numbers

In this program, you'll learn to find the largest among three numbers using if else and display it.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user
#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):
   largest = num1
elif (num2 >= num1) and (num2 >= num3):
   largest = num2
else:
   largest = num3

print("The largest number between",num1,",",num2,"and",num3,"is",largest)

Output

The largest number between 10, 14 and 12 is 14.0

Note: To test the program, change the values of num1, num2 and num3.

Check Prime Number

Example to check whether an integer is a prime number or not using for loop and if...else statement. If the number is not prime, it's explained in output why it is not a prime number.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python program to check if the input number is prime or not

num = 407

# take input from the user
# num = int(input("Enter a number: "))

# prime numbers are greater than 1
if num > 1:
   # check for factors
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")
       
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")

Output

407 is not a prime number
11 times 37 is 407

In this program, variable num is checked if it's prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the number is not prime. Else the number is prime.

We can decrease the range of numbers where we look for factors.

In the above program, our search range is from 2 to num - 1.

We could have used the range, [2, num / 2] or [2, num ** 0.5]. The later range is based on the fact that a composite number must have a factor less than square root of that number; otherwise the number is prime.

You can change the value of variable num in the above source code and test for other integers (if you want).

Print all Prime Numbers in an Interval

In this program, you'll learn to print all prime numbers within an interval using for loops and display it.

To understand this example, you should have the knowledge of following Python programming topics:

2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6

Source Code

# Python program to display all the prime numbers within an interval

# change the values of lower and upper for a different result
lower = 900
upper = 1000

# uncomment the following lines to take input from the user
#lower = int(input("Enter lower range: "))
#upper = int(input("Enter upper range: "))

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):
   # prime numbers are greater than 1
   if num > 1:
       for i in range(2,num):
           if (num % i) == 0:
               break
       else:
           print(num)

Output

Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997

Here, we store the interval as lower for lower interval and upper for upper interval, and find prime numbers in that range. Visit this page to understand the code to check for prime numbers.

Find the Factorial of a Number

In this article, you'll learn to find the factorial of a number and display it.

To understand this example, you should have the knowledge of following Python programming topics:

For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.

Source Code

# Python program to find the factorial of a number provided by the user.

# change the value for a different result
num = 7

# uncomment to take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

Output

The factorial of 7 is 5040

Note: To test the program, change the value of num. Try negative numbers as well.

Here, the number whose factorial is to be found is stored in num and we check if the number is negative, zero or positive using if...elif...else statement. If the number is positive, we use for loop and range() function to calculate the factorial.

Display the multiplication Table

This program displays the multiplication table of variable num (from 1 to 10).

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

''' Python program to find the
multiplication table (from 1 to 10)'''

num = 12

# To take input from the user
# num = int(input("Display multiplication table of? "))

# use for loop to iterate 10 times
for i in range(1, 11):
   print(num,'x',i,'=',num*i)

Output

12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

To iterate 10 times, for loop along with the range() function is used. The arguments inside range function is (1, 11) meaning, greater than or equal to 1 and less than 11 (meaning 10).

We have displayed the multiplication table of variable num (which is 12 in our case). You can change the value of num in the above program to test out for other values.

Print the Fibonacci sequence

In this program, you'll learn to print the Fibonacci sequence using while loop.

To understand this example, you should have the knowledge of following Python programming topics:

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.

Source Code

# Program to display the Fibonacci sequence up to n-th term where n is provided by the user

# change this value for a different result
nterms = 10

# uncomment to take input from the user
#nterms = int(input("How many terms? "))

# first two terms
n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence upto",nterms,":")
   while count < nterms:
       print(n1,end=' , ')
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1

Output

Fibonacci sequence upto 10 :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Note: To test this program, change the value of nterms.

Here, we store the number of terms in nterms. We initialize the first term to 0 and the second term to 1.

If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms. We then interchange the variables (update it) and continue on with the process.

You can also solve this problem using recursion: Python program to print the Fibonacci sequence using recursion.

Check Armstrong Number

In this example, you will learn to check whether an n-digit integer is an Armstrong number or not.

To understand this example, you should have the knowledge of following Python programming topics:

abcd... = an + bn + cn + dn + ...

In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:

153 = 1*1*1 + 5*5*5 + 3*3*3  // 153 is an Armstrong number.

Source Code: Check Armstrong number (for 3 digits)

# Python program to check if the number provided by the user is an Armstrong number or not

# take input from the user
# num = int(input("Enter a number: "))

# initialize sum
sum = 0

# find the sum of the cube of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10

# display the result
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

Output 1

Enter a number: 663
663 is not an Armstrong number

Output 2

Enter a number: 407
407 is an Armstrong number

Here, we ask the user for a number and check if it is an Armstrong number.

We need to calculate the sum of cube of each digit. So, we initialize the sum to 0 and obtain each digit number by using the modulus operator %. Remainder of a number when it is divide by 10 is the last digit of that number. We take the cubes using exponent operator.

Finally, we compare the sum with the original number and conclude that it is Armstrong number if they are equal.

Source Code: Check Armstrong number of n digits

num = 1634

# Changed num variable to string, 
# and calculated the length (number of digits)
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10

# display the result
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

You can change the value of num in the source code and run again to test it.

Find Armstrong Number in an Interval

Example to find all Armstrong numbers between two integers. To solve this problem, we have used nested loop and if statement.

To understand this example, you should have the knowledge of following Python programming topics:

abcd... = an + bn + cn + dn + ...

For example,

153 = 1*1*1 + 5*5*5 + 3*3*3  // 153 is an Armstrong number.

Visit this page to learn how you can check whether a number is an Armstrong number or not in Python.

Source Code

# Program to check Armstrong numbers in certain interval

lower = 100
upper = 2000

# To take input from the user
# lower = int(input("Enter lower range: "))
# upper = int(input("Enter upper range: "))

for num in range(lower, upper + 1):

   # order of number
   order = len(str(num))
    
   # initialize sum
   sum = 0

   # find the sum of the cube of each digit
   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** order
       temp //= 10

   if num == sum:
       print(num)

Output

153
370
371
407
1634

Here, we have set the lower limit 100 in variable lower and upper limit 2000 in variable upper. We have used for loop to iterate from variable lower to upper. In iteration, the value of lower is increased by 1 and checked whether it is an Armstrong number or not.

You can change the range and test out by changing the variables lower and upper. Note, the variable lower should be lower than upper for this program to work properly.

Find the Sum of Natural Numbers

In this program, you'll learn to find the sum of n natural numbers using while loop and display it.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python program to find the sum of natural numbers up to n where n is provided by user

# change this value for a different result
num = 16

# uncomment to take input from the user
#num = int(input("Enter a number: "))

if num < 0:
   print("Enter a positive number")
else:
   sum = 0
   # use while loop to iterate un till zero
   while(num > 0):
       sum += num
       num -= 1
   print("The sum is",sum)

Output

The sum is 136

Note: To test the program, change the value of num.

Here, we store the number in num and display the sum of natural numbers up to that number. We use while loop to iterate until the number becomes zero.

We could have solved the above problem without using any loops using a formula directly.

Your turn: Modify the above program to find the sum of natural numbers using the formula below.

n*(n+1)/2

For example, if n = 16, the sum would be (16*17)/2 = 136.

Display Powers of 2 Using Anonymous Function

In this program, you'll learn to display powers of the integer 2 using Python anonymous function.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python Program to display the powers of 2 using anonymous function

# Change this value for a different result
terms = 10

# Uncomment to take number of terms from user
#terms = int(input("How many terms? "))

# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))

# display the result

print("The total terms is:",terms)
for i in range(terms):
   print("2 raised to power",i,"is",result[i])

Output

The total terms is: 10
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512

Find Numbers Divisible by Another Number

In this program, you'll learn to find the numbers divisible by another number and display it.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python Program to find numbers divisible by thirteen from a list using anonymous function

# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]

# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))

# display the result
print("Numbers divisible by 13 are",result)

Output

Numbers divisible by 13 are [65, 39, 221]

Convert Decimal to Binary, Octal and Hexadecimal

In this program, you'll learn to convert decimal to binary, octal and hexadecimal, and display it.

To understand this example, you should have the knowledge of following Python programming topics:

A number with the prefix '0b' is considered binary, '0o' is considered octal and '0x' as hexadecimal. For example:

60 = 0b11100 = 0o74 = 0x3c

Source Code

# Python program to convert decimal number into binary, octal and hexadecimal number system

# Change this line for a different result
dec = 344

print("The decimal value of",dec,"is:")
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")

Output

The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

Note: To test the program, change the value of dec in the program.

In this program, we have used built-in functions bin(), oct() and hex() to convert the given decimal number into respective number systems.

These functions take an integer (in decimal) and return a string.

Find ASCII Value of Character

In this program, you'll learn to find the ASCII value of a character and display it.

To understand this example, you should have the knowledge of following Python programming topics:

It is a numeric value given to different characters and symbols, for computers to store and manipulate. For example: ASCII value of the letter 'A' is 65.

Source Code

# Program to find the ASCII value of the given character

# Change this value for a different result
c = 'p'

# Uncomment to take character from user
#c = input("Enter a character: ")

print("The ASCII value of '" + c + "' is",ord(c))

Output 1

The ASCII value of 'p' is 112

Note: To test the program, change the value of c.

Here we have used ord() function to convert a character to an integer (ASCII value). This function actually returns the Unicode code point of that character.

Unicode is also an encoding technique that provides a unique number to a character. While ASCII only encodes 128 characters, current Unicode has more than 100,000 characters from hundreds of scripts.

Your turn: Modify the code above to get character from the ASCII value using the chr() function as shown below.

>>> chr(65)
'A'
>>> chr(120)
'x'
>>> chr(ord('S') + 1)
'T'

Here, ord() and chr() are built-in functions. Visit here to know more about built-in functions in Python.

Find HCF or GCD

In this example, you will learn to find the GCD of two numbers using two different methods: function and loops and, Euclidean algorithm

To understand this example, you should have the knowledge of following Python programming topics:

Source Code: Using Loops

# Python program to find the H.C.F of two input number

# define a function
def computeHCF(x, y):

# choose the smaller number
    if x > y:
        smaller = y
    else:
        smaller = x
    for i in range(1, smaller+1):
        if((x % i == 0) and (y % i == 0)):
            hcf = i
            
    return hcf

num1 = 54 
num2 = 24

# take input from the user
# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))

print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

Output

The H.C.F. of 54 and 24 is 6

Here, two integers stored in variables num1 and num2 are passed to a function which returns the H.C.F.

In the function, we first determine the smaller of the two number since the H.C.F can only be less than or equal to the smallest number. We then use a for loop to go from 1 to that number.

In each iteration, we check if our number perfectly divides both the input numbers. If so, we store the number as H.C.F. At the completion of the loop we end up with the largest number that perfectly divides both the numbers.

The above method is easy to understand and implement but not efficient. A much more efficient method to find the H.C.F. is the Euclidean algorithm.

Euclidean algorithm

This algorithm is based on the fact that H.C.F. of two numbers divides their difference as well.

In this algorithm, we divide the greater by smaller and take the remainder. Now, divide the smaller by this remainder. Repeat until the remainder is 0.

For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24. The remainder is 6. Now, we divide 24 by 6 and the remainder is 0. Hence, 6 is the required H.C.F.

Source Code: Using Euclidean Algorithm

def computeHCF(x, y):

   # This function implements the Euclidian algorithm to find H.C.F. of two numbers
   while(y):
       x, y = y, x % y

   return x

computeHCF(300, 400)

Here we loop until y becomes zero. The statement x, y = y, x % y does swapping of values in Python. Click here to learn more about swapping variables in Python.

In each iteration, we place the value of y in x and the remainder (x % y) in y, simultaneously. When y becomes zero, we have H.C.F. in x.

Find LCM

In this program, you'll learn to find the LCM of two numbers and display it.

To understand this example, you should have the knowledge of following Python programming topics:

For example, the L.C.M. of 12 and 14 is 84.

Source Code: Without using GCD function

# Python Program to find the L.C.M. of two input number

# define a function
def lcm(x, y):
   """This function takes two
   integers and returns the L.C.M."""

   # choose the greater number
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm

# change the values of num1 and num2 for a different result
num1 = 54
num2 = 24

# uncomment the following lines to take input from the user
#num1 = int(input("Enter first number: "))
#num2 = int(input("Enter second number: "))

print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

Output

The L.C.M. of 54 and 24 is 216

Note: To test this program, change the values of num1 and num2.

This program stores two number in num1 and num2 respectively, and passes them to a function which returns the L.C.M.

In the function, we first determine the greater of the two number since the L.C.M. can only be greater than or equal to the largest number. We then use an infinite while loop to go from that number and beyond.

In each iteration, we check if both the input numbers perfectly divides our number. If so, we store the number as L.C.M. and break from the loop. Otherwise, the number is incremented by 1 and the loop continues.

The above program is slower to run. We can make it more efficient by using the fact that the product of two numbers is equal to the product of least common multiple and greatest common divisor of those two numbers.

Number1 * Number2 = L.C.M. * G.C.D.

Here is a Python program to implement this.

Source Code: Using GCD function

# Python program to find the L.C.M. of two input number

# define gcd function
def gcd(x, y):
   """This function implements the Euclidian algorithm
   to find G.C.D. of two numbers"""

   while(y):
       x, y = y, x % y

   return x

# define lcm function
def lcm(x, y):
   """This function takes two
   integers and returns the L.C.M."""

   lcm = (x*y)//gcd(x,y)
   return lcm

# change the values of num1 and num2 for a different result
num1 = 54
num2 = 24 

# uncomment the following lines to take input from the user
#num1 = int(input("Enter first number: "))
#num2 = int(input("Enter second number: "))

print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

Note: To test this program, change the values of num1 and num2.

The output of this program is same as before. We have two functions gcd() and lcm(). We require G.C.D. of the numbers to calculate its L.C.M.

So, lcm() calls the function gcd() to accomplish this. G.C.D. of two numbers can be calculated efficiently using the Euclidean algorithm.

Click here to learn more about methods to calculate G.C.D in Python.

Find Factors of Number

In this program, you'll learn to find the factors of a number using a for loop and display it.

To understand this example, you should have the knowledge of following Python programming topics:

# Python Program to find the factors of a number

# define a function
def print_factors(x):
   # This function takes a number and prints the factors

   print("The factors of",x,"are:")
   for i in range(1, x + 1):
       if x % i == 0:
           print(i)

# change this value for a different result.
num = 320

# uncomment the following line to take input from the user
#num = int(input("Enter a number: "))

print_factors(num)

Output

The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320

Note: To test the program, change the value of num.

In this program, the number whose factor is to be found is stored in num.

Then we display its factors using the function print_factors(). In the function, we use a for loop to iterate from 1 to that number and only print it if, it perfectly divides our number. Here, print_factors() is a user-defined function.

Visit here to learn more about user-defined function in Python.

Make a Simple Calculator

In this example you will learn to create a simple calculator that can add, subtract, multiply or divide depending upon the input from the user.

To understand this example, you should have the knowledge of following Python programming topics:

''' Program make a simple calculator that can add, subtract, multiply and divide using functions '''

# This function adds two numbers 
def add(x, y):
   return x + y

# This function subtracts two numbers 
def subtract(x, y):
   return x - y

# This function multiplies two numbers
def multiply(x, y):
   return x * y

# This function divides two numbers
def divide(x, y):
   return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user 
choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")

Output

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210

In this program, we ask the user to choose the desired operation. Options 1, 2, 3 and 4 are valid. Two numbers are taken and an if...elif...else branching is used to execute a particular section. User-defined functions add(), subtract(), multiply() and divide() evaluate respective operations.

Shuffle Deck of Cards

In this program, you'll learn to shuffle a deck of cards using random module.

To understand this example, you should have the knowledge of following Python programming topics:

# Python program to shuffle a deck of card using the module random and draw 5 cards

# import modules
import itertools, random

# make a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))

# shuffle the cards
random.shuffle(deck)

# draw five cards
print("You got:")
for i in range(5):
   print(deck[i][0], "of", deck[i][1])

Output

You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade

Note: Run the program again to shuffle the cards.

In program, we used the product() function in itertools module to create a deck of cards. This function performs the Cartesian product of the two sequence.

The two sequence are, numbers from 1 to 13 and the four suits. So, altogether we have 13 * 4 = 52 items in the deck with each card as a tuple. For e.g. deck[0] = (1, 'Spade').

Our deck is ordered, so we shuffle it using the function shuffle() in random module.

Finally, we draw the first five cards and display it to the user. We will get different output each time you run this program as shown in our two outputs.

Here we have used the standard modules itertools and random that comes with Python.

Display Calendar

Python has a built-in function, calendar to work with date related tasks. You will learn to display the calendar of a given date in this example.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python program to display calendar of given month of the year

# import module
import calendar

yy = 2014
mm = 11

# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar
print(calendar.month(yy, mm))

Output


  November 2014
Mo Tu We Th Fr Sa Su
               1  2
3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

You can change the value of variables yy and mm and run it to test this program for other dates.

Display Fibonacci Sequence Using Recursion

In this program, you'll learn to display Fibonacci sequence using a recursive function.

To understand this example, you should have the knowledge of following Python programming topics:

The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms.This means to say the nth term is the sum of (n-1)th and (n-2)th term.


Source Code

# Python program to display the Fibonacci sequence up to n-th term using recursive functions

def recur_fibo(n):
   """Recursive function to
   print Fibonacci sequence"""
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))

# Change this value for a different result
nterms = 10

# uncomment to take input from the user
#nterms = int(input("How many terms? "))

# check if the number of terms is valid
if nterms <= 0:
   print("Plese enter a positive integer")
else:
   print("Fibonacci sequence:")
   for i in range(nterms):
       print(recur_fibo(i))

Output

Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Note: To test the program, change the value of nterms.

In this program, we store the number of terms to be displayed in nterms.

A recursive function recur_fibo() is used to calculate the nth term of the sequence. We use a for loop to iterate and calculate each term recursively.

Visit here to know more about recursion in Python.

Find Sum of Natural Numbers Using Recursion

In this program, you'll learn to find the sum of natural numbers using recursive function.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Python program to find the sum of natural numbers up to n using recursive function

def recur_sum(n):
   """Function to return the sum
   of natural numbers using recursion"""
   if n <= 1:
       return n
   else:
       return n + recur_sum(n-1)

# change this value for a different result
num = 16

# uncomment to take input from the user
#num = int(input("Enter a number: "))

if num < 0:
   print("Enter a positive number")
else:
   print("The sum is",recur_sum(num))

Output

The sum is 136

Note: To test the program, change the value of num. Try negative numbers as well.

Find Factorial of Number Using Recursion

In this program, you'll learn to find the factorial of a number using recursive function.

To understand this example, you should have the knowledge of following Python programming topics:

For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.

Source Code

# Python program to find the factorial of a number using recursion

def recur_factorial(n):
   """Function to return the factorial
   of a number using recursion"""
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

# Change this value for a different result
num = 7

# uncomment to take input from the user
#num = int(input("Enter a number: "))

# check is the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of",num,"is",recur_factorial(num))

Output

The factorial of 7 is 5040

Note: To test the program, change the value of num.

Here, the number is stored in num and use recursive function recur_factorial() to compute the product up to that number.

Convert Decimal to Binary Using Recursion

In this program, you will learn to convert decimal number to binary using recursive function.

To understand this example, you should have the knowledge of following Python programming topics:

How to convert decimal to binary?

Source Code

def convertToBinary(n):
   """Function to print binary number
   for the input decimal using recursion"""
   if n > 1:
       convertToBinary(n//2)
   print(n % 2,end = '')

# decimal number
dec = 34

convertToBinary(dec)

Output

110100

You can change the variable dec in the above program and run it to test out for other values.

Add Two Matrices

In this program, you'll learn to add two matrices using Nested loop and Next list comprehension, and display it.

To understand this example, you should have the knowledge of following Python programming topics:

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0].

We can perform matrix addition in various ways in Python. Here are a couple of them.

Source code: Matrix Addition using Nested Loop

# Program to add two matrices using nested loop

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

result = [[0,0,0],
         [0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]

for r in result:
   print(r)

Output

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

In this program we have used nested for loops to iterate through each row and each column. At each point we add the corresponding elements in the two matrices and store it in the result.

Source Code: Matrix Addition using Nested List Comprehension

# Program to add two matrices
# using list comprehension

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

result = [[X[i][j] + Y[i][j]  for j in range(len(X[0]))] for i in range(len(X))]

for r in result:
   print(r)

The output of this program is the same as above. We have used nested list comprehension to iterate through each element in the matrix.

List comprehension allows us to write concise codes and we must try to use them frequently in Python. They are very helpful.

Transpose a Matrix

In this example, you will learn to transpose a matrix (which is created by using a nested list).

To understand this example, you should have the knowledge of following Python programming topics:

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0].

Transpose of a matrix is the interchanging of rows and columns. It is denoted as X'. The element at ith row and jth column in X will be placed at jth row and ith column in X'. So if X is a 3x2 matrix, X' will be a 2x3 matrix.

Here are a couple of ways to accomplish this in Python.

Matrix Transpose using Nested Loop

Source Code

# Program to transpose a matrix using nested loop

X = [[12,7],
    [4 ,5],
    [3 ,8]]

result = [[0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[j][i] = X[i][j]

for r in result:
   print(r)

Output

[12, 4, 3]
[7, 5, 8]

In this program we have used nested for loops to iterate through each row and each column. At each point we place the X[i][j] element into result[j][i].

Matrix Transpose using Nested List Comprehension

Source Code

''' Program to transpose a matrix using list comprehension'''

X = [[12,7],
    [4 ,5],
    [3 ,8]]

result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]

for r in result:
   print(r)

The output of this program is the same as above. We have used nested list comprehension to iterate through each element in the matrix.

List comprehension allows us to write concise codes and we must try to use them frequently in Python. They are very helpful.

Multiply Two Matrices

In this example you will learn to multiply matrices using two different ways: nested loop and, nested list comprenhension

To understand this example, you should have the knowledge of following Python programming topics:

We can treat each element as a row of the matrix.

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0].

Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y.

If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the dimension n x l (but YX is not defined). Here are a couple of ways to implement matrix multiplication in Python.

Source Code: Matrix Multiplication using Nested Loop

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print(r)

Output

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

In this program, we have used nested for loops to iterate through each row and each column. We accumulate the sum of products in the result.

This technique is simple but computationally expensive as we increase the order of matrix.

For larger matrix operations we recommend optimized software packages like NumPy which is several (in the order of 1000) times faster than the above code.

Source Code: Matrix Multiplication Using Nested List Comprenhension

# Program to multiply two matrices using list comprehension

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]

# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]

for r in result:
   print(r)

The output of this program is the same as above. To understand the above code we must first know about built-in function zip() and unpacking argumnet list using * operator.

We have used nested list comprehension to iterate through each element in the matrix. The code looks complicated and unreadable at first. But once you get the hang of list comprehensions, you will probably not go back to nested loops.

Check Whether a String is Palindrome or Not

In this program. you'll learn to check whether a string is palindrome or Not

To understand this example, you should have the knowledge of following Python programming topics:

For example: "dad" is the same in forward or reverse direction. Another example is "aibohphobia" which literally means, an irritable fear of palindromes.

Source Code

# Program to check if a string
#  is palindrome or not

# change this value for a different output
my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison
my_str = my_str.casefold()

# reverse the string
rev_str = reversed(my_str)

# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
   print("It is palindrome")
else:
   print("It is not palindrome")

Output

It is palindrome

Note: To test the program, change the value of my_str in the program.

In this program, we have taken a string stored in my_str.

Using the method casefold() we make it suitable for caseless comparisons. Basically, this method returns a lowercased version of the string.

We reverse the string using the built-in function reversed(). Since this function returns a reversed object, we use the list() function to convert them into a list before comparing.

Remove Punctuations From a String

This program removes all punctuations from a string. We will check each character of the string using for loop. If the character is a punctuation, empty string is assigned to it.

To understand this example, you should have the knowledge of following Python programming topics:

In such cases, we may first want to clean up the string and remove all the punctuation marks. Here is an example of how it is done.

Source Code

# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user
# my_str = input("Enter a string: ")

# remove punctuation from the string
no_punct = ""
for char in my_str:
   if char not in punctuations:
       no_punct = no_punct + char

# display the unpunctuated string
print(no_punct)

Output

Hello he said and went

In this program, we first define a string of punctuations. Then, we iterate over the provided string using a for loop.

In each iteration, we check if the character is a punctuation mark or not using the membership test. We have an empty string to which we add (concatenate) the character if it is not a punctuation. Finally, we display the cleaned up string.

Sort Words in Alphabetic Order

In this program, you'll learn to sort the words in alphabetic order using for loop and display it.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Program to sort alphabetically the words form a string provided by the user

# change this value for a different result
my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user
#my_str = input("Enter a string: ")

# breakdown the string into a list of words
words = my_str.split()

# sort the list
words.sort()

# display the sorted words

print("The sorted words are:")
for word in words:
   print(word)

Output

The sorted words are:
Example
Hello
Is
With
an
cased
letters
this

Note: To test the program, change the value of my_str.

In this program, we store the string to be sorted in my_str. Using the split() method the string is converted into a list of words. The split() method splits the string at whitespaces.

The list of words is then sorted using the sort() method and all the words are displayed.

Illustrate Different Set Operations

In this example, we have defined two set variables and we have performed different set operations: union, intersection, difference and symmetric difference.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code

# Program to perform different set operations like in mathematics

# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};

# set union
print("Union of E and N is",E | N)

# set intersection
print("Intersection of E and N is",E & N)

# set difference
print("Difference of E and N is",E - N)

# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)

Output

Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}

In this program, we take two different sets and perform different set operations on them. This can equivalently done by using set methods.

Count the Number of Each Vowel

In this program, you'll learn to count the number of each vowel in a string using dictionary and list comprehension.

To understand this example, you should have the knowledge of following Python programming topics:

Source Code: Using Dictionary

# Program to count the number of each vowel in a string

# string of vowels
vowels = 'aeiou'

# change this value for a different result
ip_str = 'Hello, have you tried our turorial section yet?'

# uncomment to take input from the user
#ip_str = input("Enter a string: ")

# make it suitable for caseless comparisions
ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)

# count the vowels
for char in ip_str:
   if char in count:
       count[char] += 1

print(count)

Output

{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}

Note: To test this program, change the value of ip_str.

We use the dictionary method fromkeys() to construct a new dictionary with each vowel as its key and all values equal to 0. This is initialization of the count.

Next we iterate over the input string using a for loop.

In each iteration we check if the character is in the dictionary keys (True if it is a vowel) and increment the value by 1 if true.

Source Code: Using a list and a dictionary comprehension

# Program to count the number of
# each vowel in a string using
# dictionary and list comprehension

# change this value for a different result
ip_str = 'Hello, have you tried our turorial section yet?'

# uncomment to take input from the user
#ip_str = input("Enter a string: ")

# make it suitable for caseless comparisions
ip_str = ip_str.casefold()

# count the vowels
count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}

print(count)

The ouput of this program is the same as above.

Here, we have nested a list comprehension inside a dictionary comprehension to count the vowels in a single line.

However, this program is slower as we iterate over the entire input string for each vowel.

Merge Mails

In this program, you'll learn to merge mails into one.

To understand this example, you should have the knowledge of following Python programming topics:

Mail merge is a process of doing this. Instead of writing each mail separately, we have a template for body of the mail and a list of names that we merge together to form all the mails.

Source Code to Merge Mails

# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt

# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:

   # open body.txt for reading
   with open("body.txt",'r',encoding = 'utf-8') as body_file:
   
       # read entire content of the body
       body = body_file.read()

       # iterate over names
       for name in names_file:
           mail = "Hello "+name+body

           # write the mails to individual files
           with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
               mail_file.write(mail)

For this program, we have written all the names in separate lines in the file "names.txt". The body is in the "body.txt" file.

We open both the files in reading mode and iterate over each name using a for loop. A new file with the name "[name].txt" is created, where name is the name of that person.

We use strip() method to clean up leading and trailing whitespaces (reading a line from the file also reads the newline '\n' character). Finally, we write the content of the mail into this file using the write() method.

Learn more about files in Python.

Find the Size (Resolution) of a Image

You will learn to find resolution of a jpeg image in this example without using external libraries

To understand this example, you should have the knowledge of following Python programming topics:

Most of the file formats have headers (initial few bytes) which contain useful information about the file.

For example, jpeg headers contain information like height, width, number of color (grayscale or RGB) etc. In this program, we find the resolution of a jpeg image reading these headers, without using any external library.

Source Code of Find Resolution of JPEG Image

def jpeg_res(filename):
   """"This function prints the resolution of the jpeg image file passed into it"""

   # open image for reading in binary mode
   with open(filename,'rb') as img_file:

       # height of image (in 2 bytes) is at 164th position
       img_file.seek(163)

       # read the 2 bytes
       a = img_file.read(2)

       # calculate height
       height = (a[0] << 8) + a[1]

       # next 2 bytes is width
       a = img_file.read(2)

       # calculate width
       width = (a[0] << 8) + a[1]

   print("The resolution of the image is",width,"x",height)

jpeg_res("img1.jpg")

Output

The resolution of the image is 280 x 280

In this program, we opened the image in binary mode. Non-text files must be open in this mode. The height of the image is at 164th position followed by width of the image. Both are 2 bytes long.

Note that this is true only for JPEG File Interchange Format (JFIF) standard. If your image is encode using other standard (like EXIF), the code will not work.

We convert the 2 bytes into a number using bitwise shifting operator <<. Finally, the resolution is displayed.

Find Hash of File

In this article, you'll learn to find the hash of a file and display it.

To understand this example, you should have the knowledge of following Python programming topics:

They are widely used in cryptography for authentication purposes. There are many hashing functions like MD5, SHA-1 etc. Refer this page to know more about hash functions in cryptography.

In this example, we will illustrate how to hash a file. We will use the SHA-1 hashing algorithm. The digest of SHA-1 is 160 bits long.

We do not feed the data from the file all at once, because some files are very large to fit in memory all at once. Breaking the file into small chunks will make the process memory efficient.

Source Code to Find Hash

# Python rogram to find the SHA-1 message digest of a file

# import hashlib module
import hashlib

def hash_file(filename):
   """"This function returns the SHA-1 hash
   of the file passed into it"""

   # make a hash object
   h = hashlib.sha1()

   # open file for reading in binary mode
   with open(filename,'rb') as file:

       # loop till the end of the file
       chunk = 0
       while chunk != b'':
           # read only 1024 bytes at a time
           chunk = file.read(1024)
           h.update(chunk)

   # return the hex representation of digest
   return h.hexdigest()

message = hash_file("track1.mp3")
print(message)

Output

633d7356947eec543c50b76a1852f92427f4dca9

In this program, we open the file in binary mode. Hash functions are available in the hashlib module. We loop till the end of the file using a while loop. On reaching the end, we get empty bytes object.

In each iteration we only read 1024 bytes (this value can be changed according to our wish) from the file and update the hashing function.

Finally, we return the digest message in hexadecimal representation using the hexdigest() method.